<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Ringo Chan <334258471@qq.com>
// +----------------------------------------------------------------------

namespace Admin\Controller;

/**
 * 物流接口控制器
 * 
 * @author Ringo Chan<334258471@qq.com>
 */
class ShippingController extends AdminController{
    
    /**
     * 物流公司列表
     * 
     * @author Ringo Chan <334258471@qq.com>
     */
    public function index(){
        $title       =   I('title');
        $map['status']  =   array('egt',0);
        
        if($title){
            $map['id|code|title'] =   array(intval($title),array('like','%'.$title.'%'),array('like','%'.$title.'%'),'_multi'=>true);
        }
        
        $list   = $this->lists('Shipping', $map);
        int_to_string($list);
        $this->assign('_list', $list);
        $this->meta_title = '物流费用配置';
        $this->display();
    }
    
    /**
     * 新增物流公司
     *
     * @author Ringo Chan <334258471@qq.com>
     */
    public function add(){
        if (IS_POST) {
            empty(I('post.code')) && $this->error('物流公司代号不能为空');
            !preg_match('/[\x{4e00}-\x{9fa5}A-Za-z]{1,60}+$/u', I('post.title')) && $this->error('物流公司名称长度必须在2-60个字符之间');
            empty(I('post.price')) && !is_numeric(I('post.price')) && I('post.price') < 0 && $this->error('基本费用不能小于0');
            !is_numeric(I('post.sort')) && $this->error('排序必须为数字');
    
            $M_shipping = M('shipping');
    
            $data = array(
                'code' => I('post.code'),
                'title' => I('post.title'),
                'website' => I('post.website'),
                'mobile' => I('post.mobile'),
                'price' => I('post.price'),
                'sort' => I('post.sort'),
                'create_time' => NOW_TIME,
                'update_time' => NOW_TIME,
                'status' => 1
            );
    
            $id = $M_shipping->add($data);
    
            $id ? $this->success('新增成功', U('index')) : $this->error('新增失败，未知错误');
        } else {
            $this->meta_title = '新增物流公司';
            $this->display('edit');
        }
    }
    
    /**
     * 编辑物流公司
     *
     * @param integer id 编号
     * @author Ringo Chan <334258471@qq.com>
     */
    public function edit(){
        $id = I('get.id', 0);
        
        $M_shipping = M('shipping');
        $M_shipping_price = M('shipping_price');
        
        $info = $M_shipping->find($id);
    
        !$info && $this->error('非法参数ID');
    
        if (IS_POST) {
            empty(I('post.code')) && $this->error('物流公司代号不能为空');
            !preg_match('/[\x{4e00}-\x{9fa5}A-Za-z]{1,60}+$/u', I('post.title')) && $this->error('物流公司名称长度必须在2-60个字符之间');
            empty(I('post.price')) && !is_numeric(I('post.price')) && I('post.price') < 0 && $this->error('基本费用不能小于0');
            !is_numeric(I('post.sort')) && $this->error('排序必须为数字');
    
            $data = array(
                'code' => I('post.code'),
                'title' => I('post.title'),
                'website' => I('post.website'),
                'mobile' => I('post.mobile'),
                'price' => I('post.price'),
                'sort' => I('post.sort'),
                'update_time' => NOW_TIME,
            );
    
            $status = $M_shipping->where(array('id'=>$id))->save($data);
    
            $status ? $this->success('编辑成功', U('index')) : $this->error('编辑失败，未知错误');
        } else {
            $prices = $M_shipping_price->where(array('shipping_id'=>$id))->select();
            
            $info['prices'] = $prices;
            
            $this->assign('info', $info);
            $this->meta_title = '编辑物流公司';
            $this->display('edit');
        }
    }
    
    /**
     * 增加 物流费用
     *
     * @author Ringo Chan <334258471@qq.com>
     */
    public function addShippingPrice($shipping_id = 0, $ids = 0, $price = 0){
        $M_shipping = M('shipping');
        $M_shipping_price = M('shipping_price');
    
        empty($shipping_id) && !$M_shipping->find($shipping_id) && $this->ajaxReturn(array('status'=>0, 'message'=>'非法参数'));
        empty($ids) && $this->ajaxReturn(array('status'=>0, 'message'=>'请选择选项'));
        !is_numeric($price) && $price <= 0 && $this->ajaxReturn(array('status'=>0, 'message'=>'价格不能低于1元'));
    
        !is_array($ids) && $ids = str2arr($ids);
        
        foreach ($ids as $id) {
            $info = $M_shipping_price->where(array('shipping_id'=>$shipping_id, 'province_id'=>$id))->find();
            if ($info) {
                $province = get_table_field($id, 'province_id', 'province', 'hat_province');
                $this->ajaxReturn(array('status'=>0, 'message'=>'省份：' . $province . '已存在'));
            }
        }
        
        $results = array(); 
        
        foreach ($ids as $id) {
            $result_id = $M_shipping_price->add(array('shipping_id'=>$shipping_id, 'province_id'=>$id, 'price'=>$price, 'create_time'=>NOW_TIME, 'update_time'=>NOW_TIME));
            if ($result_id <= 0) {
                $M_shipping_price->where(array('shipping_id'=>$shipping_id, 'province_id'=>array('in', $ids)))->delete();
                $this->ajaxReturn(array('status'=>0, 'message'=>'添加失败，未知错误'));
            }
            
            $province = get_table_field($id, 'province_id', 'province', 'hat_province');
            
            $results[] = array(
                'id' => $result_id,
                'province' => $province
            );
        }
    
        $this->ajaxReturn(array('status'=>1, 'message'=>'操作成功', 'data'=>$results));
    }
    
    /**
     * 修改 物流费用
     */
    public function editShippingPrice($id = 0, $price = 0) {
        $M_shipping_price = M('shipping_price');
    
        !$M_shipping_price->find($id) && $this->ajaxReturn(array('status'=>0, 'message'=>'非法参数'));
        !is_numeric($price) && $price <= 0 && $this->ajaxReturn(array('status'=>0, 'message'=>'价格不能低于1元'));
    
        $status = $M_shipping_price->where(array('id'=>$id))->setField(array('price'=>$price, 'update_time'=>NOW_TIME));
    
        $status ? $this->ajaxReturn(array('status'=>1, 'message'=>'操作成功', 'data'=>array('id'=>$id))) : array('status'=>0, 'message'=>'未知错误');
    }
    
    /**
     * 删除 物流费用
     *
     * @author Ringo Chan <334258471@qq.com>
     */
    public function deleteShippingPrice($id = 0){
        $M_shipping_price = M('shipping_price');
    
        !$M_shipping_price->find($id) && $this->ajaxReturn(array('status'=>0, 'message'=>'非法参数'));
    
        $M_shipping_price->where(array('id'=>$id))->delete();
    
        $this->ajaxReturn(array('status'=>1, 'message'=>'操作成功'));
    }
    
    /**
     * 物流接口列表
     * 
     * @author Ringo Chan <334258471@qq.com>
     */
    public function api(){
        $M_shipping_api = M('Shipping_api');
        
        $installs = $M_shipping_api->select();
        
        foreach ($installs as $key => $item){
            $installs[$item['code']] = $item;
            unset($installs[$key]);
        }
        
        $files = glob(VENDOR_PATH . 'shipping/*.php');
        
        $list = array();
        
        foreach ($files as $file) {
            $extension = basename($file, '.php');
            vendor("shipping.".$extension);
            
            $class = new $extension();

            $list[] = array(
                'code' => $class::_CODE_,
                'title' => isset($installs[$class::_CODE_]) ? $installs[$class::_CODE_]['title'] : $class::_TITLE_,
                'website' => $class::_WEBSITE_,
                'desc' => $class::_DESC_,
                'in_used' => isset($installs[$class::_CODE_]) ? $installs[$class::_CODE_]['in_used'] : 0,
                'installed' => isset($installs[$class::_CODE_]) ? 1 : 0
            );
        }
        
        $this->meta_title = '物流接口列表';
        $this->assign('_list', $list);
        $this->display();
    }
    
    /**
     * 编辑物流接口
     * 
     * @param string $code 接口代号
     * @author Ringo Chan <334258471@qq.com>
     */
    public function editApi($code = ''){
        !$code && $this->error('参数不能为空');
        
        !vendor("shipping.".$code) && $this->error('非法参数');
        
        $M_shipping_api = M('shipping_api');
        
        $info = $M_shipping_api->where(array('code'=>$code))->find();
        
        !$info && $this->error('非法参数');
        
        if (IS_POST) {
            $title = I('post.title');
            $comment = I('post.comment');
            
            !preg_match('/^[\x{4e00}-\x{9fa5}][\x{4e00}-\x{9fa5}A-Za-z0-9_-]{1,50}+$/u', $title) && $this->error('物流接口名称必须在2 - 50个字符之间，首字符必须为中文');
            !preg_match('/[\x{4e00}-\x{9fa5}A-Za-z0-9_-]{1,50}+$/u', $comment) && $this->error('备注必须在2 - 50个字符之间');
            
            $status = $M_shipping_api->where(array('code'=>$code))->save(array('title'=>$title, 'comment'=>$comment, 'update_time'=>NOW_TIME));
            
            $status ? $this->success('操作成功', U('Shipping/api')) : $this->error('操作失败，未知错误');
        } else {
            $this->meta_title = '编辑物流接口';
            $this->assign('info', $info);
            $this->display();
        }
    }
    
    /**
     * 安装物流接口
     * 
     * @param string $code 接口代号
     * @author Ringo Chan <334258471@qq.com>
     */
    public function install($code = ''){
        !$code && $this->error('参数不能为空'); 
        
        !vendor("shipping.".$code) && $this->error('非法参数');
        
        $M_shipping_api = M('shipping_api');
        
        $info = $M_shipping_api->where(array('code'=>$code))->find();
        
        $info && $this->error('已安装，请勿重复安装');
        
        $class = new $code();
        
        $installed = $M_shipping_api->add(array('code'=>$class::_CODE_, 'title'=>$class::_TITLE_, 'comment'=>$class::_DESC_, 'create_time'=>NOW_TIME, 'update_time'=>NOW_TIME));
        
        $installed ? $this->success('安装成功') : $this->error('安装失败，未知错误');
    }
    
    /**
     * 卸载物流接口
     * 
     * @param string $code 接口代号
     * @author Ringo Chan <334258471@qq.com>
     */
    public function uninstall($code = ''){
        !$code && $this->error('参数不能为空');
        
        !vendor("shipping.".$code) && $this->error('非法参数');
        
        $M_shipping_api = M('shipping_api');
        
        $M_shipping_api->where(array('code'=>$code))->delete() ? $this->success('卸载成功') : $this->error('卸载失败，未知错误');
    }
    
    /**
     * 使用物流接口
     * 
     * @param string $code 接口代号
     * @author Ringo Chan <334258471@qq.com>
     */
    public function used($code = ''){
        !$code && $this->ajaxReturn(array('status'=>0, 'message'=>'非法参数'));
        
        !vendor("shipping.".$code) && $this->ajaxReturn(array('status'=>0, 'message'=>'非法参数'));
        
        $M_shipping_api = M('shipping_api');
        
        $info = $M_shipping_api->where(array('code'=>$code))->find();
        
        !$info && $this->ajaxReturn(array('status'=>0, 'message'=>'非法参数'));
        
        $M_shipping_api->where(array('in_used'=>1))->setField('in_used', 0);
        $status = $M_shipping_api->where(array('code'=>$code))->setField('in_used', 1);
        
        $status ? $this->ajaxReturn(array('status'=>1, 'message'=>'修改成功')) : $this->ajaxReturn(array('status'=>0, 'message'=>'修改失败，未知错误'));
    }
    
    /**
     * 通用改变状态
     *
     * @param string $method 方法名
     * @param number $status 状态值
     * @param array id 编号
     * @author Ringo Chan <334258471@qq.com>
     */
    public function changeStatus($method=null, $status=0){
        $map['id'] =   array('in',I('id', 0));
        $feedback = false;
    
        switch ( strtolower($method) ){
            case 'shipping':
                $M_shipping = M('shipping');
                $data['status'] = $status;
                $feedback = $M_shipping->where($map)->save($data);
                break;
            default:
                $this->error('参数非法');
        }
    
        $feedback !== false ? $this->success('状态修改成功！') : $this->error('状态修改失败！');
    }
}
?>